<template>
    <el-drawer v-model="visible" title="直播计划详情" direction="rtl" size="50%" :before-close="handleClose"
        class="live-detail-drawer">

        <!-- 顶部标题区域 -->
        <template #header>
            <div class="drawer-header">
                <span class="drawer-title">直播计划详情</span>

                <!-- 审核状态显示 -->
                <template v-if="currentRow.audit === 'reject'">
                    <el-tag :type="getStatusTagType(currentRow.status)" effect=" dark" class="audit-tag">
                        {{ currentRow.auditText }}
                    </el-tag>
                </template>

                <template v-else-if="currentRow.audit === 'pass'">
                    <el-tag :type="getStatusTagType(currentRow.status)" effect="light" class="status-tag">
                        {{ currentRow.statusText }}
                    </el-tag>
                </template>

                <template v-else-if="currentRow.audit === 'pending'">
                    <el-tag type="warning" effect="light" class="pending-tag">
                        {{ currentRow.auditText }}
                    </el-tag>
                </template>
            </div>
        </template>

        <!-- 内容区域 -->
        <div class="reject-edit-form">
            <el-form ref="editFormRef" :model="editForm" label-width="120px" label-position="top"
                :disabled="!isEditMode">
                <el-form-item label="直播标题" prop="livestreamTitle">
                    <el-input v-model="editForm.livestreamTitle" placeholder="请输入直播标题" :readonly="!isEditMode" />
                </el-form-item>

                <el-form-item label="开播时间" prop="livestreamStartTime">
                    <el-date-picker v-model="editForm.livestreamStartTime" type="datetime" placeholder="选择开播时间"
                        format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" style="width: 100%"
                        :disabled="!isEditMode" />
                </el-form-item>

                <el-form-item label="直播封面" prop="reservationCover">
                    <el-upload class="qr-uploader" :show-file-list="false" :before-upload="beforeCoverUpload"
                        :disabled="!isEditMode">
                        <img v-if="editForm.reservationCover" :src="editForm.reservationCover" class="qr-img" />
                        <el-icon v-else class="qr-uploader-placeholder">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="直播详情" prop="detail" >
                    <el-input v-model="editForm.detail" placeholder="请输入开播信息" :readonly="!isEditMode" />
                </el-form-item>

                <el-form-item label="直播介绍" prop="livestreamIntroduce">
                    <el-input v-model="editForm.livestreamIntroduce" type="textarea" :rows="4" placeholder="请输入直播介绍内容" maxlength="500"
                        show-word-limit :readonly="!isEditMode" />
                </el-form-item>

                <el-form-item label="电话客服" prop="userTel" >
                    <el-input v-model="editForm.userTel" placeholder="请输入电话号码" :readonly="!isEditMode" />
                </el-form-item>

                <el-form-item label="企业微信客服" prop="wxQr">
                    <el-upload class="qr-uploader" :show-file-list="false" :before-upload="beforeQrUpload"
                        :disabled="!isEditMode">
                        <img v-if="editForm.wxQr" :src="editForm.wxQr" class="qr-img" />
                        <div v-else class="qr-uploader-placeholder">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <span>上传</span>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <div class="drawer-footer-container">
                <div class="drawer-footer-status" v-if="currentRow.audit === 'reject'">
                    <el-tag type="danger" effect="dark" class="audit-tag">
                        驳回原因: {{ currentRow.rejectReason || '视频与内容不符' }}
                    </el-tag>
                </div>
                <div class="drawer-footer-actions">
                    <template v-if="!isEditMode">
                        <el-button @click="handleCancelLive">取消直播</el-button>
                        <el-button type="primary" @click="visible = false">提交</el-button>
                    </template>
                    <template v-else>
                        <el-button @click="handleCancelLive">取消直播</el-button>
                        <el-button @click="visible = false">提交</el-button>
                        <el-button type="primary" @click="handleModify">修改</el-button>
                    </template>
                </div>
            </div>
        </div>
    </el-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { livestreamgetInfo } from '@/api/plan'

const props = defineProps({
    modelValue: Boolean,
    rowData: Object
})

const emit = defineEmits(['update:modelValue', 'refresh', 'delete'])

const visible = ref(false)
const editFormRef = ref(null)
const isEditMode = ref(false)

const currentRow = ref({})
const editForm = ref({
    title: '',
    startTime: '',
    cover: '',
    detail: '',
    desc: '',
    phone: '',
    wxQr: ''
})

// 初始化数据
const initData = () => {
   

    livestreamgetInfo(props.rowData.id)
        .then((res) => {
            if (res.code === 200) {
                editForm.value = res.data
                
            }
        })
        .catch((err) => {
            console.error('发送失败:', err);
        });
    // currentRow.value = {
    //     ...props.rowData,
    //     rejectReason: props.rowData.rejectReason || '视频与内容不符'
    // }

    // editForm.value = {
    //     title: props.rowData.title,
    //     startTime: props.rowData.startTime,
    //     cover: props.rowData.cover,
    //     detail: props.rowData.detail || '开播信息',
    //     desc: props.rowData.desc,
    //     phone: props.rowData.phone || '',
    //     wxQr: props.rowData.wxQr || ''
    // }

   

    // // 关键：根据 isEdit 控制是否可编辑
    // isEditMode.value = !!props.rowData.isEdit
}

watch(() => props.modelValue, val => {
    visible.value = val
    if (val) {
        // 根据当前行的审核状态决定是否进入编辑模式
        isEditMode.value = props.rowData.audit === 'reject' && props.rowData.isEdit
        initData()
    }
})

watch(visible, val => {
    emit('update:modelValue', val)
})
// 直播状态
const getStatusTagType = (status) => {
    switch (status) {
        case 'ready': return 'warning'
        case 'living': return 'primary'
        case 'end': return 'info'
        default: return ''
    }
}
defineExpose({
    getStatusTagType
})
const beforeCoverUpload = file => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('请上传图片文件')
        return false
    }
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        editForm.value.cover = reader.result
    }
    return false
}

const beforeQrUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) {
        ElMessage.error('请上传图片文件')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB')
        return false
    }
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        editForm.value.wxQr = reader.result
    }
    return false
}

// 取消直播
const handleCancelLive = () => {
    ElMessageBox.confirm('确定要取消直播吗? 此操作将删除直播数据', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        emit('delete', currentRow.value) // 这里触发delete事件
        visible.value = false
        ElMessage.success('直播已取消')
    }).catch(() => {
        // 取消操作
    })
}

// 修改数据
const handleModify = () => {
    // 表单验证
    if (!editForm.value.title || !editForm.value.startTime || !editForm.value.detail || !editForm.value.phone) {
        ElMessage.error('请填写所有必填字段')
        return
    }

    // 更新当前行数据
    const modifiedData = {
        ...currentRow.value,
        ...editForm.value,
        audit: 'pending', // 状态变为待审核
        auditText: '待审核'
    }

    ElMessage.success('修改成功，已提交审核')
    emit('refresh', modifiedData)
    visible.value = false
}

const handleClose = (done) => {
    if (isEditMode.value) {
        // 检查表单是否有修改
        const isModified = Object.keys(editForm.value).some(
            key => editForm.value[key] !== currentRow.value[key]
        )

        if (isModified) {
            ElMessageBox.confirm('您有未保存的修改，确定要关闭吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                done()
            }).catch(() => {
                // 取消关闭
            })
        } else {
            done()
        }
    } else {
        done()
    }
}
</script>

<style scoped>
.live-detail-drawer {
    .reject-edit-form {
        padding: 20px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .el-form {
            flex: 1;
            overflow-y: auto;
            padding-right: 10px;
        }

        .qr-uploader {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            width: 100px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #fafafa;

            &:hover {
                border-color: #409eff;
            }

            .qr-img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }

            .qr-uploader-placeholder {
                display: flex;
                flex-direction: column;
                align-items: center;
                color: #8c939d;

                .el-icon {
                    font-size: 28px;
                    margin-bottom: 8px;
                }
            }
        }
    }

    .drawer-header {
        display: flex;
        align-items: center;
        padding: 0 20px;
        height: 56px;
        border-bottom: 1px solid #e6e6e6;

        .drawer-title {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            margin-right: 12px;
        }

        .audit-tag {
            font-size: 12px;
            height: 24px;
            line-height: 22px;
            padding: 0 8px;
            color: #F5222D;
            background: #FFF1F0;
        }
    }

    .audit-tag {
        font-size: 12px;
        height: 24px;
        line-height: 22px;
        padding: 0 8px;
        color: #F5222D;
        background: #FFF1F0;
    }

        .pending-tag {
            color: #faad14;
            background: #fffbe6;
            border-color: #ffd591;
        }

    .drawer-footer-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #eee;
    }

    .drawer-footer-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        width: 100%;
    }
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
    font-weight: bold;
    padding-bottom: 8px;
}

/* 必填项星号样式 */
:deep(.el-form-item.is-required .el-form-item__label::before) {
    color: #f56c6c;
    margin-right: 4px;
}
</style>